<template>
  <div class="common-warp wh100 warp-bg">
    <div class="noo">
      <a-card title="职位信息">
        <!-- <template #extra><a href="#">more</a></template> -->
        <a-form ref="formRef" :model="state.form" :rules=rules>
          <a-form-item label="职位名称" name="name">
            <a-input v-model:value="state.form.name" />
          </a-form-item>
          <a-form-item label="上级部门" name="parentCode">
            <a-cascader v-model:value="state.form.parentCode" change-on-select
              :fieldNames="{ children: 'children', label: 'name', value: 'code' }" :options="state.positionTree" />
          </a-form-item>
        </a-form>
      </a-card>
    </div>
    <a-button type="primary" block @click="confirm(formRef)">提交</a-button>
  </div>
</template>

<script lang='ts' setup>
import { ref, reactive, onMounted, } from 'vue';
import { useRouter } from 'vue-router'
import { usePersonPositionCreateApi, usePersonPositionListApi } from '@/api/index'
import { message } from 'ant-design-vue';
import type { PositionItem } from '@/types/person/position';


const router = useRouter()
const formRef = ref();

const rules = {
  name: [{ required: true, message: '请输入职位名称', trigger: 'change' }],
};

const useContent = () => {
  return {
    name: "",
    parentCode: "",
  }
}

const state = reactive({
  form: useContent(),
  positionList: [],
  positionTree: [],
  parentCode: ''
})

//提交
const confirm = (formRef: any) => {
  if (!formRef) return;
  formRef.validate().then(async () => {
    if (state.form.parentCode instanceof Array) {
      state.parentCode = state.form.parentCode[state.form.parentCode.length - 1]
    }
    await usePersonPositionCreateApi({ name: state.form.name, parentCode: state.parentCode })
    message.success("操作成功", 2);
    setTimeout(() => {
      router.push({ name: 'PersonPosition' })
    }, 2300)
  })
};

onMounted(() => {
  document.title = '新增'
  getPositionList()
})

function formatTree(data: PositionItem[], parentCode: string) {
  let result = [] as any[];
  data.forEach((item: PositionItem) => {
    if (item.parentCode === parentCode) {
      let children = formatTree(data, item.code)
      if (children.length === 0) {
        children = null
      }
      item.children = children
      result.push(item)
    }
  });
  return result;
}


const getPositionList = async () => {
  let { data } = await usePersonPositionListApi()
  state.positionTree = formatTree(data, '')
  state.positionList = data
}

</script>
<style scoped lang='less'>
.noo {
  height: calc(100vh - 56px);
  overflow-y: scroll;

  :deep(.ant-form-item-label) {
    padding: 0 !important;
  }

  :deep(.ant-card-body) {
    padding: 12px !important;
  }

  :deep(.ant-card-head) {
    padding: 12px !important;
  }

  :deep(.ant-form-item) {
    margin-bottom: 12px !important;
  }

}
</style>